package com.hqq.persistence_tier.repository;

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * PersonSpecifications
 * 帮助类
 * Created by heqianqian on 2017/8/14.
 */
public class PersonSpecifications {

    public static class AgeBetweenSpec implements Specification<Person> {

        private int from;

        private int to;

        public AgeBetweenSpec(int from, int to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
            return criteriaBuilder.between(root.get("age"), from, to);
        }
    }

    public static class NameEqualSpec implements Specification<Person>{

        private String name;

        public NameEqualSpec(String name) {
            this.name = name;
        }

        @Override
        public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
            return criteriaBuilder.equal(root.get("name"),name);
        }
    }
}
